package com.gzx.plugin.tjzy.modular.qianwen.util;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationOutput;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gzx.plugin.tjzy.modular.qianwen.constant.IntentType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.List;

/**
 * 提示词助手工具类
 */
@Slf4j
public class IntentPromptUtil {

    private IntentPromptUtil() {
    }

    //分析意图
    public static String analyzeIntent(String userMessage, String apiKey, JSONArray list) {
        String intentStr = "";
        try {
            String prompt = buildIntentAnalysisPrompt(userMessage, list);
            GenerationResult rsp = callQwen(prompt, apiKey);
            GenerationOutput output = rsp.getOutput();
            List<GenerationOutput.Choice> choices = output.getChoices();
            for (GenerationOutput.Choice choice : choices) {
                Message message = choice.getMessage();
                //message里面包含 ```json{"intent"：""}```
                intentStr = message.getContent();
                //替换掉```，剩下的内容可以转成json
                if (!ObjectUtils.isEmpty(intentStr)) {
                    intentStr = intentStr.replace("```json", "").replace("```", "");
                }
            }
            log.info("intentStr {}", intentStr);
            if (!ObjectUtils.isEmpty(intentStr)) {
                JSONObject json = JSON.parseObject(intentStr);
                intentStr = json.getString("intent");
            }
        } catch (Exception e) {
            log.error("意图识别失败: {}", e.getMessage());
            return "意图识别失败";
        }
        if (ObjectUtils.isEmpty(intentStr)) {
            //未匹配到意图返回默认
            log.info("未匹配到意图");
            return "未匹配到意图";
        }
        return intentStr;
    }

    //调用模型
    public static GenerationResult callQwen(String prompt, String apiKey) throws NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(prompt)
                .build();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                //apiKey配置到nacos里面
                .apiKey(apiKey)
                .model(IntentType.MODEL)
                .messages(Collections.singletonList(userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        return gen.call(param);
    }

    //构造提示词
    public static String buildIntentAnalysisPrompt(String userMessage, JSONArray list) {
        //获取数据字典，把意图告诉ai
        StringBuilder sb = new StringBuilder(IntentType.PROMPT);
        for (int i = 0; i < list.size(); i++) {
            JSONObject js = list.getJSONObject(i);
            sb.append(js.getString("dictValue")).append(":").append(js.getString("dictLabel")).append("。");
        }
        sb.append("用户消息: ").append(userMessage);
        return sb.toString();
    }

}
